from itsdangerous import BadData
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
from django.conf import settings


def generate_save_user_token(openid):
    # serializer = Serializer(秘钥, 有效期秒)
    serializer = Serializer(settings.SECRET_KEY, 300)
    # serializer.dumps(数据), 返回bytes类型
    token = serializer.dumps({'openid': openid})
    return token


def check_save_user_token(access_token):
    """使用Itsdangrous提取access_token中的openID"""
    # serializer = Serializer(秘钥, 有效期秒)
    serializer = Serializer(settings.SECRET_KEY, 300)
    try:
        data = serializer.loads(access_token)
    except BadData:
        # 验证失败，会抛出itsdangerous.BadData异常
        return None
    # 校验成功，返回access_token中的openID
    return data['openid']
